// 获取pt_key
import nextFetch from '../../utils/nextFetch';
import consts from '../../utils/consts'
import qs from "query-string";
import { filterObject } from "../../utils/utils";
import fetch from "isomorphic-unfetch";

export default async function handler (req, res) {
  let pt_key = "xxx"
  let pt_pin = "abc"
  let cookie = "pt_key:" + pt_key + ";pt_pin:" + pt_pin
  let result = {
    pt_key: pt_key,
    pt_pin: pt_pin,
    cookie: cookie
  }
  // let reqBooks = await getStaticProps();
  // 获取token
  let reqBooks = await getToken(consts.ws_key);
  result.getToken = reqBooks
  if (!reqBooks || reqBooks['code'] !== '0' || !reqBooks['tokenKey']) {
    res.status(500).json(reqBooks)
    return
  }
  let tokenKey = reqBooks['tokenKey']
  // 跳转获取pt_key
  // let jmpResult = await appjmp(tokenKey);
  // result.appjmp = jmpResult
  res.status(200).json(result)
}

async function getStaticProps () {
  // get all books
  // const reqBooks = await fetch(`https://anjnc.com`)
  // const chapters = reqBooks.text()
  const chapters = await nextFetch.getH('https://anjnc.com');
  console.log('consts.ws_key', consts.ws)
  return chapters
}

async function getToken (ws) {
  let sign = '53904736db53eebc01ca70036e7187d6'
  let header = {
    'cookie': ws,
    'User-Agent': 'okhttp/3.12.1;jdmall;android;version/10.1.2;build/89743;screen/1440x3007;os/11;network/wifi;',
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'charset': 'UTF-8',
    'accept-encoding': 'br,gzip,deflate'
  }
  let query = {
    'functionId': 'genToken',
    'clientVersion': '10.1.2',
    'client': 'android',
    'lang': 'zh_CN',
    'uuid': '09d53a5653402b1f',
    'st': '1630392618706',
    'sign': sign,
    'sv': '120'
  }
  let data = 'body=%7B%22action%22%3A%22to%22%2C%22to%22%3A%22https%253A%252F%252Fplogin.m.jd.com%252Fcgi-bin%252Fm%252Fthirdapp_auth_page%253Ftoken%253DAAEAIEijIw6wxF2s3bNKF0bmGsI8xfw6hkQT6Ui2QVP7z1Xg%2526client_type%253Dandroid%2526appid%253D879%2526appup_type%253D1%22%7D&'
  let url = 'https://api.m.jd.com/client.action'
  url += '?functionId=genToken'
  url += '&clientVersion=10.1.2'
  url += '&client=android'
  url += '&lang=zh_CN'
  url += '&uuid=09d53a5653402b1f'
  url += '&st=1630392618706'
  url += '&sign=' + sign
  url += '&sv=120'
  let result = await nextFetch.post(url, {data, header});
  // console.log('getToken.result:', result)
  return result
}

async function appjmp (token) {
  let header = {
    'User-Agent': 'jdapp;android;10.1.2;11;0393465333165363-5333430323261366;network/wifi;model/M2102K1C;addressid/938507929;aid/09d53a5653402b1f;oaid/2acbcab5bb3f0e68;osVer/30;appBuild/89743;partner/lc023;eufv/1;jdSupportDarkMode/0;Mozilla/5.0 (Linux; Android 11; M2102K1C Build/RKQ1.201112.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045714 Mobile Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
  }
  let query = {
    'tokenKey': token,
    'to': 'https://plogin.m.jd.com/cgi-bin/m/thirdapp_auth_page?token=' + token,
    'client_type': 'android',
    'appid': 879,
    'appup_type': 1,
  }
  let url = 'https://un.m.jd.com/cgi-bin/app/appjmp'

  let opts = {
    method: 'get',
    headers: header,
    timeout: 5000,
    mode: 'no-cors',
    credentials: 'omit',
    redirect: 'manual'
  };

  if (query) {
    url += `${url.includes('?') ? '&' : '?'}${qs.stringify(
      filterObject(query, Boolean),
    )}`;
  }
  let headers = await fetch(url, opts).then(res => res.headers)
  console.log('appjmp.url:', url)
  console.log('appjmp.opts:', opts)
  console.log('appjmp.set-cookie:', headers.get('set-cookie'))

  // let result = await nextFetch.get(url, {query, header});
  // console.log('appjmp.result:', result)
  return headers
}
